package com.geek.statistics.util;

import com.geek.statistics.beans.RequestInfo;
import com.geek.statistics.beans.RequestStat;

import java.util.List;

public class Aggregator {
    public static RequestStat aggregate(List<RequestInfo> requestInfos, long durationInMillis) {
        double maxRespTime = Double.MIN_VALUE;
        double minRespTime = Double.MAX_VALUE;
        double avgRespTime = -1;
        double p999RespTime = -1;
        double p99RespTime = -1;
        double sumRespTime = 0;
        long count = 0;

        // 计算最大值最小值
        for (RequestInfo requestInfo : requestInfos) {
            ++count;
            double respTime = requestInfo.getResponseTime();
            if (maxRespTime < respTime) {
                maxRespTime = respTime;
            }
            if (minRespTime > respTime) {
                minRespTime = respTime;
            }
            sumRespTime += respTime;
        }
        // 计算平均值
        if (count != 0) {
            avgRespTime = sumRespTime / count;
        }
        // 计算tps
        long tps = count / durationInMillis * 1000;
        // 计算TP99、TP999
        requestInfos.sort((o1, o2) -> Double.compare(o1.getResponseTime() - o2.getResponseTime(), 0.0));
        int idx999 = (int) (count * 0.999);
        int idx99 = (int) (count * 0.99);
        if (count != 0) {
            p999RespTime = requestInfos.get(idx999).getResponseTime();
            p99RespTime = requestInfos.get(idx99).getResponseTime();
        }

        return RequestStat.builder()
                .maxResponseTime(maxRespTime)
                .avgResponseTime(avgRespTime)
                .minResponseTime(minRespTime)
                .p99ResponseTime(p99RespTime)
                .p999ResponseTime(p999RespTime)
                .count(count)
                .tps(tps).build();
    }
}
